#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m'

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查环境
check_environment() {
    log_info "检查环境..."

    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装"
        exit 1
    fi

    # 检查Docker服务
    if ! docker info &> /dev/null; then
        log_error "Docker服务未启动"
        exit 1
    }

    # 检查Maven
    if ! command -v mvn &> /dev/null; then
        log_error "Maven未安装"
        exit 1
    }

    # 检查Java
    if ! command -v java &> /dev/null; then
        log_error "Java未安装"
        exit 1
    }

    log_info "环境检查通过"
}

# 初始化Docker Swarm
init_swarm() {
    log_info "初始化Docker Swarm..."

    # 检查Swarm状态
    if ! docker info | grep -q "Swarm: active"; then
        # 初始化Swarm
        if ! docker swarm init --advertise-addr 127.0.0.1 &> /dev/null; then
            log_error "Swarm初始化失败"
            exit 1
        fi
        log_info "Swarm初始化成功"
    else
        log_info "Swarm已经处于活动状态"
    fi
}

# 构建项目
build_project() {
    log_info "构建项目..."

    # 编译deployer
    log_info "编译deployer..."
    if ! go build -o bin/deployer cmd/deployer/main.go; then
        log_error "编译失败"
        exit 1
    fi
    log_info "编译成功"
}

# 部署测试项目
deploy_test_project() {
    log_info "部署测试项目..."

    # 部署参数
    local service="test-project"
    local repo="internal/deployer/testdata/test-project"
    local branch="main"
    local port="8080"
    local env="test"

    # 执行部署
    log_info "执行部署命令..."
    if ! ./bin/deployer \
        --service ${service} \
        --repo ${repo} \
        --branch ${branch} \
        --port ${port} \
        --env ${env} \
        --debug \
        --health-check true \
        --health-endpoint /check; then
        log_error "部署失败"
        exit 1
    fi

    # 等待服务启动
    log_info "等待服务启动..."
    sleep 10

    # 检查服务状态
    log_info "检查服务状态..."
    if ! docker service ls | grep -q "${service}"; then
        log_error "服务未创建"
        exit 1
    fi

    # 检查服务健康状态
    log_info "检查服务健康状态..."
    local retries=0
    local max_retries=30
    while [ $retries -lt $max_retries ]; do
        if curl -s http://localhost:${port}/check | grep -q "OK"; then
            log_info "服务健康检查通过"
            break
        fi
        retries=$((retries + 1))
        sleep 2
    done

    if [ $retries -eq $max_retries ]; then
        log_error "服务健康检查失败"
        exit 1
    fi
}

# 清理环境
cleanup() {
    log_info "清理环境..."

    # 删除服务
    if docker service ls | grep -q "test-project"; then
        docker service rm test-project
    fi

    # 清理工作目录
    if [ -d ".deployer" ]; then
        rm -rf .deployer
    fi

    log_info "清理完成"
}

# 主函数
main() {
    # 注册清理函数
    trap cleanup EXIT

    # 执行测试步骤
    check_environment
    init_swarm
    build_project
    deploy_test_project

    log_info "测试完成"
}

# 执行主函数
main "$@"
